
//
//  MainViewController.m
//  Weibo
//
//  Created by taoshanchang on 15/1/21.
//  Copyright (c) 2015年 taoshanchang. All rights reserved.
//

#import "MainViewController.h"
#import "HomeViewController.h"
#import "MessageViewController.h"
#import "ProfileViewController.h"
#import "DiscoverViewController.h"
#import "MoreViewController.h"
#import "BaseNavigationController.h"
#import "ThemeButton.h"
#import "UIFaactory.h"
#import "UIViewExt.h"
#import "CONSTS.h"

#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width

@interface WBBaseRequest ()
- (void)debugPrint;
@end

@interface WBBaseResponse ()
- (void)debugPrint;
@end

@interface MainViewController ()

@end

@implementation MainViewController


-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
       [self.tabBar setHidden:YES];
        
    }
    return self;

}

- (void)viewDidLoad {

    [super viewDidLoad];
    [self _initViewController];
    [self initTabBarView];
    //每60秒请求未读数据
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - UI

//初始化控制器
-(void)_initViewController{
    
    _homeViewController  = [[HomeViewController alloc] init];
    MessageViewController *messageViewController = [[MessageViewController alloc] init];
    ProfileViewController *profileViewController = [[ProfileViewController alloc] init];
    DiscoverViewController *discoverViewController = [[DiscoverViewController alloc] init];
    MoreViewController *moreViewController = [[MoreViewController alloc] init];

    NSArray *views = @[_homeViewController,messageViewController,profileViewController,discoverViewController,moreViewController];
    NSMutableArray *viewControllers = [NSMutableArray arrayWithCapacity:5];
    for (UIViewController  *viewController in views) {
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:viewController];
        [viewControllers addObject:nav];
        nav.delegate = self;
    }
    
    self.viewControllers = viewControllers;

}

-(void)initTabBarView{
    _tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-49, ScreenWidth, 49)];
    
    //先改为用自定义的主题imageView来做为tabbar的背景
    [self.view addSubview:_tabBarView];
    //_tabBarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background"]];
    
    UIImageView *tabBarGroundImageView= [UIFaactory createImageView:@"tabbar_background"];
    tabBarGroundImageView.frame = _tabBarView.bounds;
    [_tabBarView addSubview:tabBarGroundImageView];
    
    
    NSArray *background = @[@"tabbar_home",@"tabbar_message_center",@"tabbar_profile",@"tabbar_discover",@"tabbar_more"];
    NSArray *heightLightBackground = @[@"tabbar_home_highlighted",@"tabbar_message_center_highlighted",@"tabbar_profile_highlighted",@"tabbar_discover_highlighted",@"tabbar_more_highlighted"];
    
    for (int i = 0; i <background.count; i++) {
        NSString *backImage = background[i];
        NSString *heightBackImage = heightLightBackground[i];
        //1、最开始的时候用的是系统的uibutton
        //UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //2、后改用带有主题切换的自定义button
        //ThemeButton *button = [[ThemeButton alloc] initWithImage:backImage heighlighted:heightBackImage];
        //3、最后使用工厂类去创建button
        UIButton *button = [UIFaactory createButton:backImage hightlighted:heightBackImage];
        button.showsTouchWhenHighlighted = YES;
        button.frame = CGRectMake((ScreenWidth/5-30)/2+i*(ScreenWidth/5), (49-30)/2, 30, 30);
        button.tag = i;
        
        //[button setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
        //[button setImage:[UIImage imageNamed:heightBackImage] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(selectedTab:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:button];
    }
    //页面指示器
    _sliderView = [UIFaactory createImageView:@"tabbar_slider"];
    _sliderView.backgroundColor = [UIColor clearColor];
    _sliderView.frame = CGRectMake((64-15)/2, 5, 15, 44);
    [_tabBarView addSubview:_sliderView];
}

-(void)refreshUnReadView:(id) result{
    //NSNumber *status = [NSNumber numberWithInt:100];
    NSNumber *status = [result objectForKey:@"status"];
    if(_badgeView == nil){
    
        _badgeView = [UIFaactory createImageView:@"main_badge"];
        _badgeView.frame = CGRectMake(_tabBarView.width/5-30, 5, 20, 20);
        [_tabBarView addSubview:_badgeView];
        
        ThemeLabel *label = [UIFaactory createLabel:kThemeListLabel];

        label.font = [UIFont systemFontOfSize:12.0f];
        label.frame = _badgeView.bounds;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        label.tag = 2015;
        [_badgeView addSubview:label];
        
    }
    int number = [status intValue];
    if(number > 0){
        
        if(number > 99){
            number = 99;
        }
        ThemeLabel *statusCount = (ThemeLabel *)[_badgeView viewWithTag:2015];
        statusCount.text = [NSString stringWithFormat:@"%d",number];
        _badgeView.hidden = NO;
    }else{
        _badgeView.hidden = YES;
    }
}

-(void)showBadge:(BOOL)show{
    _badgeView.hidden = show;

}
//影藏菜单栏
-(void)showTabbar:(BOOL)show{
    [UIView animateWithDuration:0.35 animations:^{
        if(show){
            _tabBarView.left = 0;
        }else{
            _tabBarView.left = -ScreenWidth;
        }
    }];
    
    [self _resizeView:show];

}

-(void)_resizeView:(BOOL)showTabbar{
    for(UIView *subView in self.view.subviews){
        if([subView isKindOfClass:NSClassFromString(@"UITransitionView")]){
            if(showTabbar){
                subView.height = ScreenHeight -49-20;
            }else{
                subView.height = ScreenHeight -20;
            }
        
        }
    
    }

}

#pragma mark - actions
-(void)selectedTab:(UIButton *)button{
    float x = button.left + (button .width-_sliderView.width)/2;
    [UIView animateWithDuration:0.2 animations:^{
        _sliderView.left = x;
    }];
    
    if(button.tag == self.selectedIndex  && button.tag == 0){
    
        [self loadUnReadData];
        [_homeViewController refreshWeibo];
    }
        
    self.selectedIndex = button.tag;
}

-(void)timerAction:(NSTimer *)timer{
    [self loadUnReadData];
}


#pragma mark - data


-(void)loadUnReadData{
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"SinaWeiboAuthData"][@"accessTokenKey"];
    //NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"uid", nil];
    [WBHttpRequest requestWithAccessToken:accessToken url:@"https://rm.api.weibo.com/2/remind/unread_count.json" httpMethod:@"GET" params:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        [self refreshUnReadView:result];
    }];
}



#pragma mark - SinaWeibo delegate
/**
 收到一个来自微博客户端程序的请求
 
 收到微博的请求后，第三方应用应该按照请求类型进行处理，处理完后必须通过 [WeiboSDK sendResponse:] 将结果回传给微博
 @param request 具体的请求对象
 */
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    
    NSLog(@"didReceiveWeiboRequest");
}

/**
 收到一个来自微博客户端程序的响应
 
 收到微博的响应后，第三方应用可以通过响应类型、响应的数据和 WBBaseResponse.userInfo 中的数据完成自己的功能
 @param response 具体的响应对
 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
  if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:[(WBAuthorizeResponse *)response accessToken], @"accessTokenKey",[(WBAuthorizeResponse *)response userID],@"userIDKey",nil];
        [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [_homeViewController loadWeiboData];
        
    }
}

#pragma mark - UINavigationController delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    long count = navigationController.viewControllers.count;
    if(count == 1){
        [self showTabbar:YES];
    }else{
        [self showTabbar:NO];
    }
}

@end
